<?php

namespace app\admin\controller;

use app\admin\model\order\Detail;
use app\admin\model\OrderInfo as ModelOrderInfo;
use app\common\controller\Backend;
use Exception;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class OrderInfo extends Backend
{

    /**
     * OrderInfo模型对象
     * @var \app\admin\model\OrderInfo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\OrderInfo;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    // ->with(['detail'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['order_no','status','order_total','order_num','ctime','order_desc','client_no','client_name', 'finish_time', 'client_add','saleman_name']);
                // $row->visible(['detail']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function detail($ids)
    {
        $row = Detail::where(['order_no' => $ids])->select();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 重写import方法
     */
    public function import()
    {
        set_time_limit(100);
        $file = $this->request->request('file'); //'file'为文件字段名
        $data = $this->readFile($file);
        array_push($data, []);

        $order_info = [];
        $order_detail = [];

        foreach ($data as $row) {
            if (empty($row) || (!empty($order_info) && $order_info['invoic_no'] != $row['出库单号']) || empty($order_detail)) {
                //判断是否是空信息
                if (!empty($order_info)) {
                    //将订单信息入库
                    try {
                        $order = new ModelOrderInfo();
                        $order->data($order_info);
                        $order->save();
                    } catch (Exception $e) {
                        if ($e->getCode() == 23000) {
                            $order_info['order_no'] = 'SO' . date('YmdHis', strtotime($order_info['ctime'])) . rand(1000, 9999);
                        }

                        $order = new ModelOrderInfo();
                        $order->data($order_info);
                        $order->save();
                    }
                    

                    //将订单明细入库
                    $detail = new Detail();
                    $detail->saveAll($order_detail);

                    //重置信息
                    $order_info = [];
                    $order_detail = [];
                }

                if (empty($row)) {
                    continue;
                }

                //生成订单号
                $order_info['order_no'] = 'SO' . date('YmdHi', intval(($row['创建时间'] - 25569) * 3600 * 24)) . rand(1000, 9999);
                $order_info['invoic_no'] = $row['出库单号'];
                $order_info['ctime'] = date('Y-m-d H:i:s', intval(($row['创建时间'] - 25569) * 3600 * 24));
                $order_info['finish_time'] = !empty($row['完成时间']) ? date('Y-m-d H:i:s', intval(($row['完成时间'] - 25569) * 3600 * 24)) : null;
                $order_info['delivery_header'] = $row['送货单表头'];
                $order_info['client_no'] = $row['终端编码'];
                $order_info['client_name'] = $row['终端名称'];
                $order_info['client_add'] = $row['终端地址'];
                $order_info['client_phone'] = $row['联系电话'];
                $order_info['client_contact'] = $row['联系人'];
                $order_info['saleman_name'] = $row['业务员'];
                $order_info['saleman_phone'] = $row['业务员电话'];
                $order_info['status'] = !empty($row['完成时间']) ? 5 : 1;
                $order_info['order_total'] = 0;
                $order_info['order_num'] = 0;
            }

            if (empty($row)) {
                continue;
            }

            //处理订单明细
            $data_detail = array(
                'order_no' => $order_info['order_no'],
                'product_type' => $row['商品分类'] == '非现' ? 1 :2,
                'product_name' => $row['产品名称'],
                'product_standard' => $row['规格'],
                'product_class_name' => $row['类名'],
                'product_num' => empty($row['数量']) ? 0 : $row['数量'],
                'product_price' => empty($row['单价']) ? 0 : $row['单价'],
            );

            array_push($order_detail, $data_detail);

            $order_info['order_total'] += ($data_detail['product_num'] * $data_detail['product_price']);
            $order_info['order_num'] += $data_detail['product_num'];
            
            //do something
            // var_dump($row);exit;

        }

        $this->success('导入成功');
    }

    /**
     * 打印订单
     *
     * @return void
     */
    public function printOrder()
    {
        $ids = $this->request->get('id');
        $ids = explode(',', $ids);

        //获取订单信息
        $data = Db::name('order_info')->alias('info')->join('order_detail detail', 'info.order_no = detail.order_no', 'left')->select();

        $pdf = new \TCPDF("L", "mm", array(139, 240));
        $pdf->SetFont('stsongstdlight', '', 11);

        foreach ($data as $tmp) {
            var_dump($tmp);exit;
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
            $pdf->SetTopMargin(5);
            $pdf->SetLeftMargin(5);
            $pdf->getHeaderMargin(0);
            $pdf->setFooterMargin(0);
            $pdf->SetAutoPageBreak(true, 0);
            $pdf->AddPage();

            $pdf->writeHTML(
                '<div style="line-height: 15px;font-weight: bold;font-size: 15px;text-align: center;">'
                . $dealer_info->bill_rise .
                    '</div>',
            );

            $pdf->Ln(1);

            // $salesman = StuffAccountInfo::query()->where('dealer_key', getDealerKey())->where('user_name', $tmp['salesman_name'])->first();

            $table_head = '<div style="text-align: center;">
                    <table style="text-align: left; font-size: 10px;">
                        <tr>
                            <td width="120px">终端ID：' . $tmp['client_id'] . '</td>
                            <td width="150px">终端编号：' . $tmp['client_number'] . '</td>
                            <td width="150px">联系人：' . $tmp['client_contact'] . '</td>
                            <td width="150px">联系电话：' . $tmp['phone'] . '</td>
                        </tr>
                        <tr>
                            <td>业务员：' . $tmp['salesman_name'] . '</td>
                            <td>业务员电话：' . $tmp['salesman_phone'] . '</td>
                            <td>服务投诉电话：' . $dealer_info->hasee . '</td>
                            <td>开票日期：' . $tmp['create_time'] . '</td>
                        </tr>
                        <tr>
                            <td width="420px">客户名称：' . $tmp['client_name'] . '</td>
                            <td>订单号：' . $tmp['order_no'] . '</td>
                        </tr>
                        <tr>
                            <td width="570px">客户地址：' . $tmp['address'] . '</td>
                        </tr>
                    </table>';

            $str = '';
            $all = 0;
            foreach ($tmp['items'] as $value) {
                $str .= '<tr>';
                foreach ($value as $key => $c) {
                    $str .= '<td>' . $c . '</td>';
                    if ($key == 'num' && $value['type'] != '回收品' && $value['unit'] != '支') {
                        $all += $c;
                    }
                }
                $str .= '</tr>';
            }
            if ($tmp['apply_money'] > 0) {
                $tmp['all_money'] -= $tmp['apply_money'];
                $str .= '<tr><td>费用申请</td><td>申请</td><td>-</td><td>个</td><td></td><td>1</td><td>' . $tmp['apply_money'] . '</td><td>' . $tmp['apply_money'] . '</td></tr>';
            }

            $table_body = '<table border="1" style="text-align: center; width:360;line-height: 18px;font-size: 11px">
                        <tr>
                            <th style="width:150">商品名称</th>
                            <th style="width:100">类名</th>
                            <th style="width:80">商品分类</th>
                            <th>单位</th>
                            <th>规格</th>
                            <th>数量</th>
                            <th>单价</th> 
                            <th>总价</th>
                        </tr>' . $str . '
                        <tr>
                        <td colspan="3">金额总计  大写: &nbsp;&nbsp;&nbsp;&nbsp;   ' . self::toChineseNumber($tmp['all_money']) . '</td>
                        <td colspan="2">总件数:' . $all . '</td>
                        <td colspan="3">小写:&nbsp;&nbsp;&nbsp;&nbsp;  ' . $tmp['all_money'] . '</td>
                    </tr>
                    <tr>
                        <td colspan="3" style="border-style: none;">备注：' . $tmp['order_desc'] . '</td>
                        <td colspan="2" style="border-style: none;">送货人：' . $tmp['send_name'] .
            '</td>
                        <td colspan="3" style="border-style: none;">签收人：</td>
                    </tr>
                    </table>
                 </div>';

            $pdf->writeHTML($table_head . $table_body);

            if (getDealerKey() != '07690001') {
                if (!empty($dealer_info->wx_payment_code)) {
                    $pdf->Image($dealer_info->wx_payment_code, '', '', 24, 24, '', '', 'T');
                }

                if (!empty($dealer_info->alipay_payment_code)) {
                    $pdf->Image($dealer_info->alipay_payment_code, '50', '', 24, 24, '', '', '');
                }

                $pdf->Write(0, $dealer_info->desc, '', '', 'C');
                // $pdf->Write(0, '我司经销品牌:雪花啤酒、喜力啤酒、百威啤酒系列、毛铺劲酒、
                //             景田百岁山、椰树椰汁、天地壹号、望山楂及各品牌酒水饮料。
                //         销售单上的二维码为我司唯一收款码，其他收款方式均无效。此单转账成功后自动失效!', '', '', 'C');
            }
        }



        $pdf->Output(date('Y-m-d') . '.pdf', 'I');
    }

}
